package com.iot.gateway.utils;

import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Getter;
import org.springframework.context.MessageSource;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;

import java.time.LocalDateTime;
import java.util.Locale;

@Getter
public class ApiResult<T> {

    @Schema(description = "响应时间戳")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private final LocalDateTime timestamp = LocalDateTime.now();

    // Getters
    @Schema(description = "响应状态码")
    private int code;

    @Schema(description = "响应消息")
    private String message;

    @Schema(description = "响应数据")
    private T data;

    // 私有构造函数
    private ApiResult(int code, String message, T data) {
        this.code = code;
        this.message = message;
        this.data = data;
    }

    // 成功构建器
    public static <T> ApiResult<T> success(T data) {
        return new ApiResult<>(HttpStatus.OK.value(), "操作成功", data);
    }

    public static <T> ApiResult<T> success() {
        return new ApiResult<>(HttpStatus.OK.value(), "操作成功", null);
    }

    // 失败构建器
    public static <T> ApiResult<T> fail(int code, String message) {
        return new ApiResult<>(code, message, null);
    }

    // 带数据的失败
    public static <T> ApiResult<T> fail(int code, String message, T data) {
        return new ApiResult<>(code, message, data);
    }

    // 链式调用支持
    public ApiResult<T> withData(T data) {
        this.data = data;
        return this;
    }

    // 国际化消息支持
    public ApiResult<T> withLocalizedMessage(MessageSource messageSource, Locale locale) {
        this.message = messageSource.getMessage(this.message, null, this.message, locale);
        return this;
    }

    // 状态判断
    public boolean isSuccess() {
        return false;
    }

    // 业务异常专用（400）
    public static <T> ApiResult<T> businessFail(String message) {
        return fail(HttpStatus.BAD_REQUEST.value(), message);
    }

    // 服务端错误（500）
    public static <T> ApiResult<T> serverError(String message) {
        return fail(HttpStatus.INTERNAL_SERVER_ERROR.value(), message);
    }

    // 自定义异常映射
    public static ApiResult<?> fromException(Exception ex) {
        if (ex instanceof MethodArgumentNotValidException) {
            return fail(HttpStatus.BAD_REQUEST.value(), "参数校验失败");
        }
        return fail(HttpStatus.INTERNAL_SERVER_ERROR.value(), "系统内部错误");
    }

}
